<?php

namespace app\im\controller;

use app\common\facade\Token;
use app\common\model\Imapp;
use ba\Random;
use app\common\library\Auth as UserAuth;
use think\facade\Config;

class Auth
{
    const TOKEN_TYPE = 'im';
    const TOKEN_LOGIN_TYPE = 'user';
    //验证平台token
    public static function checkToken($access_token)
    {
        //鉴权验证
        try {
            $tokenInfo = Token::get($access_token, self::TOKEN_TYPE);
            if(!$tokenInfo){
                throw new \Exception('token is invalid');
            }
            if(!Token::check($access_token, self::TOKEN_TYPE, $tokenInfo['user_id'])){
                throw new \Exception('token is invalid');
            }
            $find = Imapp::find($tokenInfo['user_id']);
            if(empty($find)){
                throw new \Exception('token is invalid');
            }
        }catch (\Exception $e){
            return false;
        }
        return $tokenInfo['user_id'];
    }
    //验证用户登录信息
    public static function checkUserLogin($data,$appid)
    {
        $ba = [
            'code'=>0,
            'msg'=>"error",
            'data'=>null
        ];
        try {
            if($data['checkType']=='token'){
                $token = $data['user_token']??throw new \Exception('user_token不能为空');
                $info = Token::get($token);
                if(!$info){
                    throw new \Exception('token is invalid');
                }
                //验证用户token
                if(!Token::check($token, self::TOKEN_LOGIN_TYPE, $info['user_id'])){
                    throw new \Exception('token is invalid');
                }
                $ba['code'] = 1;
                $ba['msg'] = 'success';
                $ba['data'] = $info['user_id'];
            }
            if($data['checkType']=='password'){
                $password = $data['password']??throw new \Exception('password不能为空');;
                if(empty($data['username']))throw new \Exception('username不能为空');;
                $username = $data['username']."#{$appid}";
                $auth = new \app\common\library\Auth();
                $res = $auth->login($username,$password,true);
                //验证用户密码
                if($res===true){
                    $ba['code'] = 1;
                    $ba['msg'] = 'success';
                    $ba['data'] = $auth->id;
                }else{
                    throw new \Exception($auth->getError());
                }
            }

        }catch (\Exception $e){
            $ba['msg'] = $e->getMessage();
        }

        return $ba;
    }
    //刷新token
    public static function refreshUserToken($data,$appid): array
    {
        $ba = [
            'code' => 0,
            'msg' => 'error',
            'data' => null
        ];
        if(empty($data['refresh_token'])){
            $ba['msg'] = 'refresh_token不能为空';
            return $ba;
        }
        $refreshToken = Token::get($data['refresh_token']);
        if (!$refreshToken || $refreshToken['expire_time'] < time()) {
            $ba['msg'] = 'Login expired, please login again.';
            return $ba;
        }
        //换取token
        $newToken = Random::uuid();
        Token::set($newToken, UserAuth::TOKEN_TYPE, $refreshToken['user_id'], (int)Config::get('buildadmin.user_token_keep_time'));
        $ba['code'] = 1;
        $ba['msg'] = 'success';
        $ba['data'] = [
            'user_id'=>$refreshToken['user_id'],
            'access_token' => $newToken,
            'refresh_token' => $data['refresh_token'],
            'expires_in' => Config::get('buildadmin.user_token_keep_time'),
        ];
        return $ba;
    }
}